package com.broada.apm.utils;

import com.google.common.primitives.Ints;

public class IPUtils {
	/**
	 * 一般说来，网络永远是大端存储，java也是大端存储，而从C/C++发过来的是小端，所以一般来说，数据从C端过来，就调用这个方法。
	 * @param ip
	 * @return
	 */
	public static String fromLittleEndianLong(long ip){
		return fromLittleEndianInteger((int)ip);
	}
	public static String fromLittleEndianInteger(int ip){
		byte[] byteArray = Ints.toByteArray(ip);
		return (byteArray[3] & 0xff) + "." + (byteArray[2] & 0xff) + "." + (byteArray[1] & 0xff) + "." + (byteArray[0] & 0xff);
	}
	public static int toLittleEndianInteger(String ip) {
		String[] ps = ip.split("\\.");
		return (Integer.parseInt(ps[3]) << 24) | (Integer.parseInt(ps[2])<<16)  | (Integer.parseInt(ps[1])<<8) | (Integer.parseInt(ps[0]));
	}
	public static long toLittleEndianLong(String ip) {
		String[] ps = ip.split("\\.");
		return (Long.parseLong(ps[3]) << 24) | (Long.parseLong(ps[2])<<16)  | (Long.parseLong(ps[1])<<8) | (Long.parseLong(ps[0]));
	}
	public static long toLong(String ip) {
		String[] ps = ip.split("\\.");
		return (Long.parseLong(ps[0]) << 24) | (Long.parseLong(ps[1])<<16)  | (Long.parseLong(ps[2])<<8) | (Long.parseLong(ps[3]));
	}
	public static String fromLong(long ip){
		return fromInteger((int)ip);
	}
	public static String fromInteger(int ip){
		byte[] byteArray = Ints.toByteArray(ip);
		return (byteArray[0] & 0xff) + "." + (byteArray[1] & 0xff) + "." + (byteArray[2] & 0xff) + "." + (byteArray[3] & 0xff);
	}
	public static int toInteger(String ip) {
		String[] ps = ip.split("\\.");
		return (Integer.parseInt(ps[0]) << 24) | (Integer.parseInt(ps[1])<<16)  | (Integer.parseInt(ps[2])<<8) | (Integer.parseInt(ps[3]));
	}
	public static boolean isIp(String IP){//判断是否是一个IP  
        boolean b = false;  
        if(IP.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")){  
            String s[] = IP.split("\\.");  
            if(Integer.parseInt(s[0])<255)  
                if(Integer.parseInt(s[1])<255)  
                    if(Integer.parseInt(s[2])<255)  
                        if(Integer.parseInt(s[3])<255)  
                            b = true;  
        }  
        return b;  
    }
}
